﻿using ShiQuan.AppUpdateBLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ShiQuan.AppUpdater
{
    public class FrmDebug : Form
    {
        private StatusStrip sysStatusBar;
        private ToolStripStatusLabel sysStatusLabel;
        private ToolStripProgressBar sysProgressBar;
        private RichTextBox richTextBox1;

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.sysStatusBar = new System.Windows.Forms.StatusStrip();
            this.sysStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.sysProgressBar = new System.Windows.Forms.ToolStripProgressBar();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.sysStatusBar.SuspendLayout();
            this.SuspendLayout();
            // 
            // sysStatusBar
            // 
            this.sysStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.sysStatusLabel,
            this.sysProgressBar});
            this.sysStatusBar.Location = new System.Drawing.Point(0, 339);
            this.sysStatusBar.Name = "sysStatusBar";
            this.sysStatusBar.Size = new System.Drawing.Size(484, 22);
            this.sysStatusBar.SizingGrip = false;
            this.sysStatusBar.TabIndex = 2;
            // 
            // sysStatusLabel
            // 
            this.sysStatusLabel.Name = "sysStatusLabel";
            this.sysStatusLabel.Size = new System.Drawing.Size(336, 17);
            this.sysStatusLabel.Spring = true;
            this.sysStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // sysProgressBar
            // 
            this.sysProgressBar.Name = "sysProgressBar";
            this.sysProgressBar.Size = new System.Drawing.Size(100, 16);
            // 
            // richTextBox1
            // 
            this.richTextBox1.BackColor = System.Drawing.SystemColors.Info;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(0, 0);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ReadOnly = true;
            this.richTextBox1.Size = new System.Drawing.Size(484, 339);
            this.richTextBox1.TabIndex = 3;
            this.richTextBox1.Text = "";
            // 
            // FrmDebug
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(484, 361);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.sysStatusBar);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmDebug";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "应用程序更新";
            this.sysStatusBar.ResumeLayout(false);
            this.sysStatusBar.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public FrmDebug(string appPath, AppLocalInfo localInfo, AppServerInfo serverInfo)
        {
            InitializeComponent();

            this.appPath = appPath;
            this.appLocalInfo = localInfo;
            this.appServerInfo = serverInfo;
            this.Load += FrmDebug_Load;
        }
        private string appPath = string.Empty;
        private AppLocalInfo appLocalInfo = null;
        private AppServerInfo appServerInfo = null;

        private BackgroundWorker backgroundWorker1;
        private AppUpdaterBLL appUpdater = null;
        private void FrmDebug_Load(object sender, EventArgs e)
        {
            this.Text = Application.ProductName + "("+Application.ProductVersion+")";
            this.richTextBox1.Text = "";

            appUpdater = new AppUpdaterBLL();
            appUpdater.UpdateProcess += AppUpdater_UpdateProcess;

            this.backgroundWorker1 = new BackgroundWorker();
            this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
            this.backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
            this.backgroundWorker1.RunWorkerAsync();
        }

        private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string error = string.Empty;
            if (appUpdater.KillService(this.appLocalInfo, out error) == false)
                return;
            //
            if (appUpdater.Update(this.appPath, appServerInfo, out error) == false)
                return;

            appUpdater.StartService(appPath, out error);
        }

        private void AppUpdater_UpdateProcess(int index, string msg)
        {
            this.Invoke((EventHandler)delegate {
                this.sysProgressBar.Value = index % 100;
                this.richTextBox1.AppendText(msg + "\n");
                this.richTextBox1.ScrollToCaret();
            });
        }

        private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Invoke((EventHandler)delegate {
                    this.richTextBox1.AppendText("\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    this.richTextBox1.AppendText("\n运行异常：");
                    this.richTextBox1.AppendText("\n" + e.Error.ToString());
                    this.richTextBox1.AppendText("\n");
                    this.richTextBox1.ScrollToCaret();
                });
                return;
            }
            if (e.Cancelled)
                return;

            Thread.Sleep(2000);
            this.Close();
        }

    }
}
